<script setup lang="ts">
import { h, reactive, ref } from "vue"
import {
  FormInst,
  useMessage,
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NSelect,
  NInput,
  NInputNumber,
} from "naive-ui"
import { getCateList, getCouponList, addCoupon, updateCoupon, getRuleProducts } from "@api/index"
import createCoupon from "./components/createCoupon.vue"
import pagination from "@/components/pagination.vue"

const showModal = ref(false)
const message = useMessage()
const formRef = ref<FormInst | null>(null)
const editConfig = reactive({
  isEdit: false,
  echoData: {},
})
const pageConfig = reactive({
  limit: 10,
  page: 1,
})
const formValue: any = reactive({
  data: {},
})

const pageTotal = ref(0)
const dataList = reactive({
  cateList: [],
  couponList: [],
  productList: [],
  varList: [
    {
      label: "是",
      value: 1,
    },
    {
      label: "否",
      value: 0,
    },
  ],
  couponTypeList: [
    {
      label: "满送",
      value: 1,
    },
    {
      label: "满折",
      value: 2,
    },
    {
      label: "满减",
      value: 3,
    },
  ],
  couponRangeList: [
    {
      label: "全场",
      value: 1,
    },
    {
      label: "类别",
      value: 2,
    },
    {
      label: "商品",
      value: 3,
    },
  ],
})
const getProductList = async () => {
  const res: any = await getRuleProducts({})
  dataList.productList = res.data.map((item: any) => {
    const children = item.productsVos.map((it: any) => {
      return { key: it.productsId.toString(), label: it.productsName }
    })
    return {
      key: item.categoryId + item.categoryName,
      label: item.categoryName,
      children,
      disabled: true,
    }
  })
}

const handleGetCateList = async (data: any) => {
  const res: any = await getCateList(data)
  dataList.cateList = res.data?.list.map((item: any) => {
    return { key: item.cateId, label: item.cateName }
  })
}
const handleGetCouponList = async (data: any) => {
  const res: any = await getCouponList(data)
  dataList.couponList = res.data?.list
  pageTotal.value = res.data?.totalCount
}
handleGetCateList({ ...pageConfig })
handleGetCouponList({ ...pageConfig })
getProductList()
const columns = [
  {
    title: "ID",
    key: "ruleId",
  },
  {
    title: "批次名称",
    key: "batchName",
  },
  {
    title: "优惠卷名称",
    key: "couponName",
  },
  {
    title: "制卷类型",
    key: "couponType",
    render(row: any) {
      return dataList.couponTypeList.find((item: any) => item.value === row.couponType).label
    },
  },
  {
    title: "使用范围",
    key: "couponRange",
    render(row: any) {
      return dataList.couponRangeList.find((item: any) => item.value === row.couponRange).label
    },
  },
  {
    title: "是否限制发卷数量",
    key: "isLimitCount",
    render(row: any) {
      return row.isLimitCount === 0 ? "否" : "是"
    },
  },
  {
    title: "总发放数量",
    key: "receiveCount",
  },
  {
    title: "是否是互斥卷",
    key: "isMutex",
    render(row: any) {
      return row.isMutex === 0 ? "否" : "是"
    },
  },
  {
    title: "用户可领取数量",
    key: "limitCount",
    render(row: any) {
      return row.isLimitCount === 0 ? "-" : row.limitCount
    },
  },
  {
    title: "已发放数量",
    key: "assignCount",
  },
  {
    title: "已使用数量",
    key: "usedCount",
  },
  {
    title: "领取时间",
    key: "receiveStarted",
    render(row: any) {
      return `${row.receiveStarted} ~ ${row.receiveEnd}`
    },
  },
  {
    title: "使用时间",
    key: "useStated",
    render(row: any) {
      return `${row.useStated} ~ ${row.useEnd}`
    },
  },
  {
    title: "操作",
    key: "action",
    render(row: any) {
      return [
        h(
          NButton,
          {
            size: "small",
            onClick: () => {
              showModal.value = true
              editConfig.isEdit = true
              editConfig.echoData = row
            },
          },
          { default: () => "编辑" }
        ),
        // h(
        //   NButton,
        //   {
        //     size: "small",
        //     onClick: () => {
        //       handleDeleteCate([row?.cateId])
        //     }
        //   },
        //   { default: () => "删除" }
        // ),
      ]
    },
  },
]

const handleOpenModal = () => {
  showModal.value = true
}

//搜索功能
const handleSearch = () => {
  formRef.value?.validate(errors => {
    if (!errors) {
      handleGetCouponList({ ...formValue.data, page: 1, limit: 10 })
    } else {
      console.log(errors)
    }
  })
}

//弹窗确认
const modalSubmit = (data: any) => {
  if (editConfig.isEdit) {
    updateCoupon(data).then((res: any) => {
      if (res.code === 200) {
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
      handleGetCouponList({ ...pageConfig, ...formValue.data })
    })
  } else {
    addCoupon(data).then((res: any) => {
      if (res.code === 200) {
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
      handleGetCouponList({ ...pageConfig, ...formValue.data })
    })
  }

  showModal.value = false
  editConfig.isEdit = false
  editConfig.echoData = {}
}
//弹窗关闭
const modalClose = () => {
  showModal.value = false
  editConfig.isEdit = false
  editConfig.echoData = {}
}
//删除分类
// const handleDeleteCate = (data: any) => {
//   deleteCate(data).then((res: any) => {
//     if (res.code === 200) {
//       message.success(res.msg)
//     } else {
//       message.error(res.msg)
//     }
//     handleGetCouponList({ ...pageConfig })
//   })
// }

//编辑分类
const handleUpdate = (data: any) => {
  updateCoupon(data).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
    handleGetCouponList({ ...pageConfig, ...formValue.data })
    showModal.value = false
    editConfig.isEdit = false
    editConfig.echoData = {}
  })
}

//分页
const handleChangePage = () => {
  handleGetCouponList({
    ...pageConfig,
    ...formValue.data,
  })
}
</script>

<template>
  <div class="index">
    <div class="search">
      <n-form ref="formRef" inline :label-width="80" label-placement="left" :model="formValue.data">
        <n-form-item label="批次名称:" path="batchName">
          <n-input class="form_item" v-model:value="formValue.data.batchName" />
        </n-form-item>
        <n-form-item label="卷名称:" path="couponName">
          <n-input class="form_item" v-model:value="formValue.data.couponName" />
        </n-form-item>
        <n-form-item label="使用门槛:" path="threshold">
          <n-input-number class="form_item" v-model:value="formValue.data.threshold" />
        </n-form-item>
        <n-form-item label="优惠类型:" path="couponType">
          <n-select class="form_select" :options="dataList.couponTypeList" v-model:value="formValue.data.couponType" />
        </n-form-item>
        <n-form-item label="使用范围:" path="couponRange">
          <n-select class="form_select" :options="dataList.couponRangeList" v-model:value="formValue.data.couponRange" />
        </n-form-item>
        <n-form-item>
          <n-button attr-type="button" @click="handleSearch"> 搜索 </n-button>
        </n-form-item>
      </n-form>
    </div>
    <div class="table">
      <div class="table_action">
        <n-button attr-type="button" @click="handleOpenModal"> 新增优惠卷 </n-button>
      </div>
      <n-data-table :scroll-x="1800" :columns="columns" :data="dataList.couponList" :pagination="false"
        :bordered="false" />
      <pagination :pageTotal="pageTotal" :pageConfig="pageConfig" :handleChangePage="handleChangePage" />
    </div>
    <createCoupon :handleUpdate="handleUpdate" :showModal="showModal" :modalSubmit="modalSubmit" :modalClose="modalClose"
      :editConfig="editConfig" :dataList="dataList" />
  </div>
</template>

<style lang="scss" scoped>
.index {
  overflow-y: scroll; //竖向滚动
  overflow-x: scroll; //横向滚动

  .search {
    height: 100px;
    padding: 20px;
    background-color: var(--BlockBgColor);
    transition: background-color 0.3s var(--n-bezier);
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .form_select {
      width: 150px;
    }
  }

  .table {
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: var(--BlockBgColor);
    transition: background-color 0.3s var(--n-bezier);

    .table_action {
      height: 60px;
      display: flex;
      align-items: center;
    }
  }
}
</style>
